<?php
/**
 * @author liuyang
 * @version 2.0
 * @since 20160417
 * http访问处理
 */
namespace Common\Util;
class HttpUtil{
	
	const DEFAULT_TIMEOUT = 10;
	
	/**
	 * 使用curl进行GET请求
	 * 支持https
	 */
	public static function curlAuthGet($url, $username,$password,$timeout = HttpUtil::DEFAULT_TIMEOUT, $header = array()){
	    $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	    curl_setopt($ch, CURLOPT_USERPWD, 'airauthk:athk29e3'); 
	    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	    $res = curl_exec($ch); 
	    $cErr = curl_error($ch); 
	    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
	    if($res !== false && $status >= 400){
	        $res = false;
	    }
	    curl_close($ch);
	
	    return $res;
	}
	
	/**
	 * 使用curl进行GET请求
	 * 支持https
	 */
	public static function curlGet($url, $timeout = HttpUtil::DEFAULT_TIMEOUT, $header = array()){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if(!empty($header)){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		//是否https请求
		$https = substr($url, 0, 8) == "https://" ? true : false;
		if($https){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名
		}
		
		$res = curl_exec($ch);
		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if($res !== false && $status >= 400){
			$res = false;
		}
		curl_close($ch);
		
		return $res;
	}
	
	
	
	/**
	 * 使用curl进行POST请求
	 * 支持httpscurlPost
	 */
	public static function curlPost($url, $data = array(), $timeout = HttpUtil::DEFAULT_TIMEOUT, $header = array()){
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		if(!empty($header)){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		//是否https请求
		$https = substr($url, 0, 8) == "https://" ? true : false;
		if($https){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名
		}
		
		$res = curl_exec($ch);
		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if($res !== false && $status >= 400){
			$res = false;
		}
		curl_close($ch);
		
		return $res;
	}
	
	/**
	 * 使用curl进行GET请求，并且将json结果还原php类型
	 */
	public static function curlGetJson($url, $assoc = true, $timeout = HttpUtil::DEFAULT_TIMEOUT,$header){
		$res = self::curlGet($url, $timeout,$header);
		if($res !== false){
			$obj = json_decode($res, $assoc);
			return $obj;
		}else{
			return false;
		}
	}
	
	/**
	 * 使用curl进行POST请求，并且将json结果还原php类型
	 */
	public static function curlPostJson($url, $data = array(), $assoc = true, $timeout = HttpUtil::DEFAULT_TIMEOUT){
		$res = self::curlPost($url, $data, $timeout);
		if($res !== false){
			$obj = json_decode($res, $assoc);
			return $obj;
		}else{
			return false;
		}
	}
	
	/**
	 * @return false|string 文件完整路径
	 */
	public static function downloadRemoteFile($saveDir, $url, $fileName = false, $timeout = HttpUtil::DEFAULT_TIMEOUT, $header = array()){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_HEADER, TRUE);    //表示需要response header
		curl_setopt($ch, CURLOPT_NOBODY, FALSE); //表示需要response body
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if(!empty($header)){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		//是否https请求
		$https = substr($url, 0, 8) == "https://" ? true : false;
		if($https){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名
		}
		
		$res = curl_exec($ch);
		$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch); 
		if($res !== false && $status >= 400){
			return false;
		}
		
		list($rheader, $body) = explode("\r\n\r\n", $res, 2);

		//下载图片特殊处理
		if(empty($rheader) || strlen($body) < 100){
			return false;
		}
		
// 		$file = rtrim($saveDir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
		//直接写死分隔符
		$file = rtrim($saveDir, '/').'/';
		if($fileName){
			$file .= $fileName;
		}else{
			$match = array();
			$rheader = str_replace("\r", '', $rheader);
			preg_match("/filename=(.*)/", $rheader, $match);
			//log
			if(!isset($match[1])){
				$out = "\n\n{$url}\n\n{$res}\n\n";
				//file_put_contents('/application/data/logs/download.error', $out, FILE_APPEND);
			}
			$fileName = (isset($match[1])) ? str_replace("'", '', str_replace("\"", '', str_replace("\r", "", $match[1]))) : time().rand(1,1000);
			$file .= $fileName;
		} 
		$wres = @file_put_contents($file, $body); 
		if($wres === false){
			return false;
		}
		return $file;
	}
	
	/**
	 * linux下使用wget命令下载
	 * 高效
	 */
	public static function downloadByWget($saveDir, $url, $fileName){
		$url = str_replace('&', '\&', $url);
		
		// 		$file = rtrim($saveDir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
		//直接写死分隔符
		$file = rtrim($saveDir, '/').'/';
		$file .= $fileName;
		
		$output = shell_exec("wget {$url} -O {$file}");
	}
}

